<!-- src/views/CourseSelectionView.vue -->
<template>
  <div class="course-selection">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>学生选课中心</h2>
      <div class="user-info">
        <span>欢迎，{{ currentUser.username }}（{{ getRoleText(currentUser.role) }}）</span>
      </div>
    </div>

    <!-- 选项卡切换 -->
    <div class="tab-container">
      <div class="tabs">
        <button 
          :class="['tab', activeTab === 'available' ? 'active' : '']"
          @click="activeTab = 'available'"
        >
          可选课程
        </button>
        <button 
          :class="['tab', activeTab === 'enrolled' ? 'active' : '']"
          @click="activeTab = 'enrolled'"
        >
          已选课程
        </button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="filters">
      <div class="search-box">
        <input 
          v-model="searchParams.courseName" 
          placeholder="搜索课程名称..."
          class="search-input"
          @keyup.enter="loadCourses"
        >
        <input 
          v-model="searchParams.courseCode" 
          placeholder="搜索课程代码..."
          class="search-input"
          @keyup.enter="loadCourses"
        >
        <select v-model="searchParams.credits" class="credit-select">
          <option value="">全部学分</option>
          <option value="1">1学分</option>
          <option value="2">2学分</option>
          <option value="3">3学分</option>
          <option value="4">4学分</option>
        </select>
        <button class="btn-search" @click="loadCourses">搜索</button>
        <button class="btn-reset" @click="resetSearch">重置</button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content-area">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <p>⏳ 正在加载课程数据...</p>
      </div>

      <!-- 可选课程列表 -->
      <div v-else-if="activeTab === 'available'" class="course-list">
        <h3>可选课程列表</h3>
        <div v-if="availableCourses.length > 0" class="courses-grid">
          <div 
            v-for="course in availableCourses" 
            :key="course.id" 
            class="course-card"
          >
            <div class="course-header">
              <h4>{{ course.courseName }}</h4>
              <span class="course-code">{{ course.courseCode }}</span>
            </div>
            <div class="course-info">
              <p><strong>学分：</strong>{{ course.credits }} 学分</p>
              <p><strong>状态：</strong>
                <span :class="['status-badge', course.status === 1 ? 'active' : 'inactive']">
                  {{ course.status === 1 ? '可选' : '不可选' }}
                </span>
              </p>
              <p><strong>创建时间：</strong>{{ formatDate(course.createTime) }}</p>
              <p v-if="course.description" class="course-description">
                {{ course.description }}
              </p>
            </div>
            <div class="course-actions">
              <button 
                class="btn-enroll" 
                @click="enrollCourse(course.id)"
                :disabled="course.status !== 1"
              >
                {{ course.status === 1 ? '选择课程' : '课程不可选' }}
              </button>
            </div>
          </div>
        </div>
        <div v-else class="empty-state">
          <div class="empty-icon">📚</div>
          <p>暂无可选课程</p>
        </div>
      </div>

      <!-- 已选课程列表 -->
      <div v-else class="enrolled-courses">
        <h3>已选课程列表</h3>
        <div v-if="enrolledCourses.length > 0" class="courses-table">
          <table class="data-table">
            <thead>
              <tr>
                <th>课程代码</th>
                <th>课程名称</th>
                <th>学分</th>
                <th>选课时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="course in enrolledCourses" :key="course.id">
                <td>{{ course.courseCode }}</td>
                <td>{{ course.courseName }}</td>
                <td>{{ course.credits }}</td>
                <td>{{ formatDate(course.selectionTime) }}</td>
                <td>
                  <span class="status-badge enrolled">已选</span>
                </td>
                <td>
                  <button class="btn-withdraw" @click="withdrawCourse(course.id)">
                    退选
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div v-else class="empty-state">
          <div class="empty-icon">🎓</div>
          <p>暂无已选课程</p>
          <p>快去选择你感兴趣的课程吧！</p>
        </div>
      </div>
    </div>

    <!-- 分页控件 -->
    <div v-if="pagination.total > 0" class="pagination">
      <button :disabled="pagination.current === 1" @click="prevPage">上一页</button>
      <span>第 {{ pagination.current }} 页 / 共 {{ pagination.pages }} 页 (共 {{ pagination.total }} 条记录)</span>
      <button :disabled="pagination.current === pagination.pages" @click="nextPage">下一页</button>
    </div>

    <!-- 操作结果提示 -->
    <div v-if="operationMessage" :class="['operation-message', operationType]">
      {{ operationMessage }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useUserStore } from '@/stores/user';
import { courseApi } from '@/api/course';

export default {
  name: 'CourseSelectionView',
  setup() {
    const userStore = useUserStore();
    const activeTab = ref('available'); // 'available' 或 'enrolled'
    const loading = ref(false);
    const availableCourses = ref([]);
    const enrolledCourses = ref([]);
    const operationMessage = ref('');
    const operationType = ref(''); // 'success' 或 'error'
    
    const searchParams = ref({
      current: 1,
      size: 12,
      courseName: '',
      courseCode: '',
      credits: ''
    });
    
    const pagination = ref({
      current: 1,
      size: 12,
      total: 0,
      pages: 0
    });

    // 获取当前用户信息
    const currentUser = computed(() => {
      return userStore.userInfo || { username: '学生', role: 'student' };
    });

    const showMessage = (message, type = 'success') => {
      operationMessage.value = message;
      operationType.value = type;
      setTimeout(() => {
        operationMessage.value = '';
        operationType.value = '';
      }, 3000);
    };

    const loadAvailableCourses = async () => {
      loading.value = true;
      try {
        console.log('🚀 加载可选课程...', searchParams.value);
        const response = await courseApi.getAvailableCourses(searchParams.value);
        console.log('📨 可选课程响应:', response.data);
        
        if (response.data.code === '000000') {
          availableCourses.value = response.data.data || [];
          pagination.value.total = response.data.total || availableCourses.value.length;
          pagination.value.pages = Math.ceil(pagination.value.total / searchParams.value.size);
        } else {
          console.error('❌ 获取可选课程失败:', response.data.msg);
          availableCourses.value = getMockAvailableCourses();
        }
      } catch (error) {
        console.error('💥 加载可选课程失败:', error);
        availableCourses.value = getMockAvailableCourses();
      } finally {
        loading.value = false;
      }
    };

    const loadEnrolledCourses = async () => {
      loading.value = true;
      try {
        console.log('🚀 加载已选课程...', searchParams.value);
        const response = await courseApi.getEnrolledCourses(searchParams.value);
        console.log('📨 已选课程响应:', response.data);
        
        if (response.data.code === '000000') {
          enrolledCourses.value = response.data.data || [];
          // 为已选课程添加选课时间（模拟数据）
          enrolledCourses.value.forEach(course => {
            course.selectionTime = course.selectionTime || new Date().toISOString();
          });
        } else {
          console.error('❌ 获取已选课程失败:', response.data.msg);
          enrolledCourses.value = getMockEnrolledCourses();
        }
      } catch (error) {
        console.error('💥 加载已选课程失败:', error);
        enrolledCourses.value = getMockEnrolledCourses();
      } finally {
        loading.value = false;
      }
    };

    const loadCourses = () => {
      if (activeTab.value === 'available') {
        loadAvailableCourses();
      } else {
        loadEnrolledCourses();
      }
    };

    // 模拟数据 - 可选课程
    const getMockAvailableCourses = () => {
      return [
        {
          id: 1,
          courseCode: 'CS101',
          courseName: '计算机基础',
          credits: 3,
          status: 1,
          description: '计算机科学入门课程，涵盖基础概念和编程原理',
          createTime: '2024-01-15T10:00:00'
        },
        {
          id: 2,
          courseCode: 'MATH201',
          courseName: '高等数学',
          credits: 4,
          status: 1,
          description: '大学数学高级课程，包括微积分和线性代数',
          createTime: '2024-01-16T09:00:00'
        },
        {
          id: 3,
          courseCode: 'ENG301',
          courseName: '英语写作',
          credits: 2,
          status: 1,
          description: '提高英语写作能力的专业课程',
          createTime: '2024-01-17T11:20:00'
        },
        {
          id: 4,
          courseCode: 'PHY202',
          courseName: '大学物理',
          credits: 3,
          status: 0,
          description: '物理学基础课程，涵盖力学和电磁学',
          createTime: '2024-01-18T14:30:00'
        }
      ];
    };

    // 模拟数据 - 已选课程
    const getMockEnrolledCourses = () => {
      return [
        {
          id: 1,
          courseCode: 'CS101',
          courseName: '计算机基础',
          credits: 3,
          selectionTime: '2024-01-20T10:00:00'
        },
        {
          id: 2,
          courseCode: 'ENG301',
          courseName: '英语写作',
          credits: 2,
          selectionTime: '2024-01-21T14:30:00'
        }
      ];
    };

    const enrollCourse = async (courseId) => {
      try {
        console.log('🎯 选择课程:', courseId);
        const response = await courseApi.enrollCourse(courseId);
        
        if (response.data.code === '000000') {
          showMessage('选课成功！', 'success');
          // 刷新可选课程和已选课程列表
          loadAvailableCourses();
          if (activeTab.value === 'enrolled') {
            loadEnrolledCourses();
          }
        } else {
          throw new Error(response.data.msg);
        }
      } catch (error) {
        console.error('❌ 选课失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '选课失败';
        showMessage(`选课失败: ${errorMsg}`, 'error');
      }
    };

    const withdrawCourse = async (courseId) => {
      if (!confirm('确定要退选这门课程吗？')) {
        return;
      }
      
      try {
        console.log('🗑️ 退选课程:', courseId);
        const response = await courseApi.withdrawCourse(courseId);
        
        if (response.data.code === '000000') {
          showMessage('退选成功！', 'success');
          // 刷新已选课程列表
          loadEnrolledCourses();
          if (activeTab.value === 'available') {
            loadAvailableCourses();
          }
        } else {
          throw new Error(response.data.msg);
        }
      } catch (error) {
        console.error('❌ 退选失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '退选失败';
        showMessage(`退选失败: ${errorMsg}`, 'error');
      }
    };

    const resetSearch = () => {
      searchParams.value.courseName = '';
      searchParams.value.courseCode = '';
      searchParams.value.credits = '';
      searchParams.value.current = 1;
      loadCourses();
    };

    const prevPage = () => {
      if (searchParams.value.current > 1) {
        searchParams.value.current--;
        loadCourses();
      }
    };

    const nextPage = () => {
      if (searchParams.value.current < pagination.value.pages) {
        searchParams.value.current++;
        loadCourses();
      }
    };

    const formatDate = (dateString) => {
      if (!dateString) return '-';
      try {
        return new Date(dateString).toLocaleDateString('zh-CN');
      } catch (error) {
        return dateString;
      }
    };

    const getRoleText = (role) => {
      const roleTexts = {
        admin: '管理员',
        teacher: '教师',
        student: '学生'
      };
      return roleTexts[role] || role;
    };

    // 监听选项卡切换
    const watchActiveTab = () => {
      loadCourses();
    };

    onMounted(() => {
      console.log('📍 CourseSelectionView组件已挂载');
      loadAvailableCourses();
    });

    return {
      activeTab,
      loading,
      availableCourses,
      enrolledCourses,
      searchParams,
      pagination,
      operationMessage,
      operationType,
      currentUser,
      loadCourses,
      enrollCourse,
      withdrawCourse,
      resetSearch,
      prevPage,
      nextPage,
      formatDate,
      getRoleText,
      watchActiveTab
    };
  }
};
</script>

<style scoped>
.course-selection {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.user-info {
  color: #666;
  font-size: 14px;
}

.tab-container {
  margin-bottom: 20px;
}

.tabs {
  display: flex;
  border-bottom: 2px solid #e0e0e0;
}

.tab {
  padding: 12px 24px;
  background: none;
  border: none;
  border-bottom: 3px solid transparent;
  cursor: pointer;
  font-size: 16px;
  color: #666;
  transition: all 0.3s ease;
}

.tab.active {
  color: #3498db;
  border-bottom-color: #3498db;
  font-weight: 600;
}

.tab:hover:not(.active) {
  color: #2980b9;
  background-color: #f8f9fa;
}

.filters {
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input, .credit-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 150px;
}

.btn-search, .btn-reset {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-search {
  background-color: #2ecc71;
  color: white;
}

.btn-reset {
  background-color: #95a5a6;
  color: white;
}

.main-content-area {
  min-height: 500px;
}

.loading-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.course-list h3, .enrolled-courses h3 {
  margin-bottom: 20px;
  color: #2c3e50;
  font-size: 18px;
}

.courses-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.course-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border: 1px solid #e0e0e0;
}

.course-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.course-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  flex: 1;
}

.course-code {
  background: #e3f2fd;
  color: #1565c0;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.course-info {
  margin-bottom: 15px;
}

.course-info p {
  margin: 5px 0;
  color: #666;
  font-size: 14px;
}

.course-description {
  color: #888 !important;
  font-style: italic;
  margin-top: 10px !important;
  line-height: 1.4;
}

.course-actions {
  text-align: center;
}

.btn-enroll {
  width: 100%;
  padding: 10px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s ease;
}

.btn-enroll:hover:not(:disabled) {
  background: #2980b9;
}

.btn-enroll:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.courses-table {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.btn-withdraw {
  padding: 6px 12px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-withdraw:hover {
  background-color: #c0392b;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-badge.inactive {
  background: #ffebee;
  color: #d32f2f;
}

.status-badge.enrolled {
  background: #e3f2fd;
  color: #1565c0;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 30px;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.operation-message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 15px 20px;
  border-radius: 4px;
  color: white;
  font-weight: 500;
  z-index: 1000;
  animation: slideIn 0.3s ease;
}

.operation-message.success {
  background: #27ae60;
}

.operation-message.error {
  background: #e74c3c;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@media (max-width: 768px) {
  .courses-grid {
    grid-template-columns: 1fr;
  }
  
  .search-box {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input, .credit-select {
    min-width: auto;
  }
}
</style>